package ai4games_tests.soccer;

import game2dai.World;
import game2dai.entities.BaseEntity;
import game2dai.fsm.State;
import game2dai.fsm.Telegram;
import game2dai.steering.SBF;

public class KeeperTendGoal  extends State implements Constants {

	private static KeeperTendGoal instance = null;

	public static KeeperTendGoal state(){
		if(instance == null){
			instance = new KeeperTendGoal();
			instance.name = "Tend Goal";
		}
		return instance;
	}


	@Override
	public void enter(BaseEntity owner) {
		GoalKeeper keeper = (GoalKeeper) owner;
		keeper.targetPos.set(keeper.getRearInterposeTarget());
		keeper.AP().arriveOn(keeper.targetPos, SBF.FAST);
	}

	@Override
	public void execute(BaseEntity owner, double deltaTime, World world) {
		GoalKeeper keeper = (GoalKeeper) owner;
		keeper.targetPos.set(keeper.getRearInterposeTarget());
		keeper.AP().arriveOn(keeper.targetPos, SBF.FAST);

		if(keeper.isBallWithinRange()){//&& keeper.team.getReceivingPlayer() == null) {
			keeper.team.pitch.ball.trap(keeper);
			keeper.FSM().changeState(KeeperPutBallBackInPlay.state());
			return;
		}
		
		// If within intercept range and the other team are in control go for it
		if(keeper.isBallWithinInterceptRange() && !keeper.team.isInControl()){
			keeper.FSM().changeState(KeeperInterceptBall.state());
			return;
		}

		if(keeper.isBallWithinInterceptRange() && keeper.team.isInControl() && keeper.team.getReceivingPlayer() == null){
			keeper.FSM().changeState(KeeperInterceptBall.state());
			return;
		}

		if(keeper.tooFarFromGoalMouth() && keeper.team.isInControl()){
			keeper.FSM().changeState(PlayerReturnToRegion.state());
			return;
		}

	}

	@Override
	public void exit(BaseEntity owner) {
		GoalKeeper keeper = (GoalKeeper) owner;
		keeper.AP().arriveOff();	
	}

	@Override
	public boolean onMessage(BaseEntity owner, Telegram tgram) {
		return false;
	}


}
